import type { Context, MiddlewareHandler } from 'hono';
import type { StatusCode } from 'hono/utils/http-status';
import type { ErrorResponse, ErrorType } from '../types/error.js';
import { AppError, InternalServerError } from '../types/error.js';

export const errorHandler: MiddlewareHandler = async (c: Context, next) => {
    try {
        await next();
    } catch (error) {
        console.error('Error caught in middleware:', error);

        let response: ErrorResponse;

        if (error instanceof AppError) {
            response = {
                code: error.statusCode,
                type: error.type,
                message: error.message,
                details: error.details
            };
        } else {
            const internalError = new InternalServerError(
                error instanceof Error ? error.message : 'An unexpected error occurred'
            );
            response = {
                code: internalError.statusCode,
                type: internalError.type,
                message: internalError.message
            };
        }

        c.status(response.code as StatusCode);
        return c.json(response);
    }
}; 